package com.uex.dev.manage.admin.intercepter;

import com.google.common.cache.LoadingCache;
import com.uex.dev.manage.admin.service.IGuestLogService;
import com.uex.dev.manage.admin.service.IUserLogService;
import com.uex.dev.manage.admin.utils.LogUtil;
import com.uex.dev.manage.admin.vo.wx.OpenidInfo;
import com.uex.dev.manage.common.base.ModelResult;
import com.uex.dev.manage.common.constant.CommonConstant;
import com.uex.dev.manage.common.utils.GsonUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * @author lzs
 * @create 2024/05/13
 * @description
 */
@Slf4j
@Component
public class OpenidInterceptor implements HandlerInterceptor {

    @Resource
    private IGuestLogService guestLogService;

    @Resource
    private IUserLogService userLogService;

    @Resource(name = "openIdCache")
    private LoadingCache<String, OpenidInfo> openIdCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        log.info(request.getRequestURI());
        if (!(handler instanceof HandlerMethod) || HttpMethod.OPTIONS.name().equals(request.getMethod())) {
            return true;
        }
        String agent = request.getHeader("user-agent");
        Object session = request.getSession().getAttribute(CommonConstant.SESSION_KEY);
        // 获取openid
        String openid = "";
        // 小程序访问
        if (session != null) {
            OpenidInfo openidInfo = openIdCache.getIfPresent(session);
            if (openidInfo != null) {
                openid = openidInfo.getOpenid();
                OpenidContext.setOpenidLocal(openidInfo);
            } else {
                String responseJson = GsonUtil.toJson(ModelResult.SESSION_ERROR);
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(responseJson);
                log.error("session异常", session);
                return false;
            }
        } else {
            // 如果没有session，设置标志位
            request.setAttribute("noOpenid", true);
        }
        // 初始化LogUtil
        LogUtil.setLog(guestLogService, userLogService, agent, openid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        OpenidContext.clear();
        MDC.clear();
    }
}

